<template>
  <div class="search-bar">
    <a-space>
      <a-input-search v-model:value.trim="query.keywords" placeholder="输入角色名称搜索" style="width: 300px"
        @search="handleSearch" />
      <a-button type="primary" @click="handleCreate">新增角色</a-button>
    </a-space>
  </div>

  <a-table :columns="columns" :data-source="dataSource" :pagination="pagination" @change="pagination.handleChange"
    row-key="id" bordered class="data-content">
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.key === 'index'">
        {{ index + 1 }}
      </template>
      <template v-if="column.key === 'isDefault'">
        <a-tag :color="record.isDefault ? 'green' : 'red'">
          {{ record.isDefault ? '是' : '否' }}
        </a-tag>
      </template>
      <template v-if="column.key === 'isStatic'">
        <a-tag :color="record.isStatic ? 'green' : 'red'">
          {{ record.isStatic ? '是' : '否' }}
        </a-tag>
      </template>
      <template v-if="column.key === 'enabled'">
        <a-tag :color="record.enabled ? 'green' : 'red'">
          {{ record.enabled ? '启用' : '禁用' }}
        </a-tag>
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space :size="8">
          <a-button type="link" size="small" @click="handleEditTenant(record)">编辑</a-button>
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              <EllipsisOutlined style="font-size: 28px;" />
            </a>
            <template #overlay>

              <a-menu>
                <a-menu-item>
                  <a href="javascript:;" @click="handlePermission(record)">权限</a>
                </a-menu-item>
                <a-menu-item>
                  <a href="javascript:;">人员</a>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm title="确定要删除这个角色吗？" ok-text="确定" cancel-text="取消" @confirm="handleDeleteTenant(record)">
                    <a href="javascript:;">删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>

        </a-space>
      </template>
    </template>
  </a-table>

  <a-modal destroyOnClose :keyboard="false" :okButtonProps="{ loading: dialogEditor.loading }"
    v-model:open="dialogEditor.open" :title="dialogEditor.title" @ok="handleOk" @cancel="handleCancel" width="800px">
    <role-editor ref="editorRef" :id="dialogEditor.id" />
  </a-modal>

  <a-modal destroyOnClose :keyboard="false" :okButtonProps="{ loading: dialogViewer.loading }"
    v-model:open="dialogViewer.open" :title="dialogViewer.title" @ok="handlePermissionOk"
    @cancel="dialogViewer.open = false" width="800px">
    <permission-editor ref="permissionRef" :provider-key="dialogViewer.id" />
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import RoleEditor from './components/editor.vue';
import { RoleApi } from '@/api/services/index';
import { GetRoleInput, RoleDto } from '@/api/services/types';
import { ClientPagination, createPagedQuery, IDialogProps } from '@/api/abp';
import moment from 'moment';
import { EllipsisOutlined } from '@ant-design/icons-vue'
import PermissionEditor from './components/permission.vue'


// 模拟数据
const pagination = ref<ClientPagination>(new ClientPagination(() => {
  loadData();
}))
const dataSource = ref<Array<RoleDto>>([])
const query = reactive<GetRoleInput>({
  keywords: '',
  readOnly: true,
  sorting: 'creationTime desc,lastModificationTime desc',
  skipCount: 0,
  maxResultCount: 20
})
const dialogEditor = reactive<IDialogProps>({
  id: '',
  open: false,
  data: undefined,
  title: '',
  loading: false
})
const dialogViewer = reactive<IDialogProps>({
  id: '',
  open: false,
  data: undefined,
  title: '',
  loading: false
})
const editorRef = ref<InstanceType<typeof RoleEditor>>();
const permissionRef = ref<InstanceType<typeof PermissionEditor>>();
const loadData = function () {
  const input = createPagedQuery(pagination.value, query);
  RoleApi.getList(input).then(res => {
    const { code, data, msg } = res;
    if (code == 0) {
      dataSource.value = data.items || [];
      pagination.value.total = data.totalCount;
      pagination.value.readOnly = true;
    } else {
      message.error(msg);
    }
  })
}

const handleSearch = function () {
  pagination.value.current = 1
  loadData();
}

const handleCreate = function () {
  dialogEditor.id = '';
  dialogEditor.title = '新增角色';
  dialogEditor.open = true;
}

const handleEditTenant = function (record: RoleDto) {
  dialogEditor.id = record.id;
  dialogEditor.title = '修改角色';
  dialogEditor.open = true;
}

const handleDeleteTenant = function (record: RoleDto) {
  RoleApi.delete(record.id).then(res => {
    const { code, msg } = res;
    if (code == 0) {
      message.success('删除成功');
      pagination.value.readOnly = false;
      loadData();
    } else {
      message.error(msg);
    }
  })
}

const handlePermission = function (record: RoleDto) {
  dialogViewer.id = record.id;
  dialogViewer.title = '角色权限[' + record.displayName + ']';
  dialogViewer.open = true;
}

const handlePermissionOk = function () {
  permissionRef.value?.submit().then(res => {
    const { code, msg } = res;
    if (code == 0) {
      dialogViewer.id = '';
      dialogViewer.open = false;
      message.success('授权成功')
    } else {
      message.error(msg);
    }
  })
}

const handleOk = async () => {
  dialogEditor.loading = true;
  editorRef.value?.submit().then(res => {
    const { code, msg } = res;
    if (code == 0) {
      dialogEditor.open = false;
      dialogEditor.id = '';
      message.success('保存成功')
      pagination.value.readOnly = false;
      loadData();
    } else {
      message.error(msg);
    }
  }).finally(() => {
    dialogEditor.loading = false;
  })

};

const handleCancel = () => {
  dialogEditor.loading = false;
  dialogEditor.id = '';
  dialogEditor.open = false;

};




onMounted(() => {
  loadData();
})

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    width: 70
  },
  {
    title: '角色名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '显示名称',
    dataIndex: 'displayName',
    key: 'displayName'
  },
  {
    title: '是否默认',
    dataIndex: 'isDefault',
    key: 'isDefault'
  },
  {
    title: '是否系统角色',
    dataIndex: 'isStatic',
    key: 'isStatic'
  },
  {
    title: '状态',
    dataIndex: 'enabled',
    key: 'enabled'
  },
  {
    title: '最后修改人',
    dataIndex: 'lastModifierName',
    key: 'lastModifierName',
    width: 150,
    customRender({ record }) {
      if (record.lastModifierName) {
        return record.lastModifierName;
      }
      return record.creatorName;
    }
  },
  {
    title: '最后修改时间',
    dataIndex: 'lastModificationTime',
    key: 'lastModificationTime',
    width: 160,
    customRender({ record }) {
      if (record.lastModificationTime) {
        return moment(record.lastModificationTime).format('YYYY-MM-DD HH:mm:ss');
      }
      return moment(record.creationTime).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 150
  }
];

</script>

<style lang="scss" scoped>
.tenant-container {
  padding: 20px;
  background: #fff;
}

.search-bar {
  margin-bottom: 20px;
}

.data-content {
  flex: 1;

  .ant-table {
    flex: 1;
  }
}
</style>
